import 'package:flutter/material.dart';
import 'package:get/get_state_manager/src/rx_flutter/rx_obx_widget.dart';
import 'package:share_plus/share_plus.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:wan_android_flutter/common/base/base_page.dart';
import 'package:wan_android_flutter/common/resources/text_styles.dart';
import 'package:webview_flutter/webview_flutter.dart';

import 'common_web_logic.dart';

class CommonWebPage extends BasePage<CommonWebLogic> {
  CommonWebPage({super.key});

  @override
  Widget? buildTitleWidget() {
    return Obx(() {
      return Text(
        logic.state.title.value,
        style: colorData.textBlack.s18.regular,
      );
    });
  }

  @override
  List<Widget>? buildRightWidgets(BuildContext context) {
    return [
      PopupMenuButton<String>(
        itemBuilder: (BuildContext context) {
          return [
            const PopupMenuItem(
              value: 'share',
              child: Text('分享'),
            ),
            const PopupMenuItem(
              value: 'openWithBrowser',
              child: Text('用系统浏览器打开'),
            )
          ];
        },
        onSelected: (String value) async {
          if ("share" == value) {
            Share.share("玩Android分享【${logic.state.title}】: ${logic.state.initialUrl}}");
          } else {
            if (await canLaunchUrl(Uri.parse(logic.state.initialUrl.value))) {
              await launchUrl(Uri.parse(logic.state.initialUrl.value));
            }
          }
        },
        icon: const Icon(Icons.more_vert),
      ),
    ];
  }

  @override
  Widget buildContent(BuildContext context) {
    return Container(
      color: colorData.bgWhite,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Obx(() {
            if (logic.state.showProgressBar.value) {
              return LinearProgressIndicator(
                backgroundColor: colorData.bgDivider,
                color: colorData.textBlue,
                minHeight: 3,
                value: logic.state.curProgress.value * 1.0 / 100,
              );
            } else {
              return const SizedBox.shrink();
            }
          }),
          Expanded(child: WebViewWidget(key: GlobalKey(), controller: logic.controller))
        ],
      ),
    );
  }
}
